<template>
  <!-- 角色管理 -->
  <div id="MenuManage" class="content-main">
    <el-row>
      <!-- 左边的编辑框 -->
      <el-col :span="demoData === 1?12:24" style="min-height: inherit; padding: 0px 0px 0px 0px; overflow: auto">
        <el-card style="height: calc( 100vh - 85px); overflow: auto">
          <div class="btn-group title">
            <el-button v-permission="'roleManage-add'" type="primary" plain size="mini" @click="addMenu">
              <i class="el-icon-plus" /> 新增角色
            </el-button>
            <el-button type="primary" plain size="mini" @click="refreshClick">
              <i class="el-icon-refresh" /> 刷新
            </el-button>
          </div>
          <div style="border-bottom: 1px solid #000; margin-bottom: 15px" />
          <div class="permission-group">
            <el-table v-loading="listLoading" :data="tableData" border style="width: 100%; margin-bottom: 10px">
              <el-table-column prop="roleName" label="角色名" />
              <el-table-column prop="remark" label="备注" />
              <el-table-column label="操作" width="100">
                <template slot-scope="scope">
                  <el-button v-permission="'roleManage-edit'" size="small" type="text" @click="editRole(scope.row)">编辑</el-button>
                  <el-button v-permission="'roleManage-delete'" size="small" type="text" @click="deleteRole(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
      <!-- 右边的编辑框 -->
      <el-col id="rightcol" v-permission="'roleManage-add' || 'roleManage-edit'" :span="12" style="min-height: inherit; padding: 0px 0px 0px 7px">
        <el-card style="height: calc( 100vh - 85px); overflow: auto">
          <div class="form-title title" style="margin-top: -3px">
            <i class="el-icon-s-grid" style="color: rgb(24, 144, 255); font-size: 18px" />
            <span style="margin-left: 5px; margin-top: -2px">{{
              MenuName
            }}</span>
          </div>
          <div style="border-bottom: 1px solid #000; margin: 11px 0" />

          <el-form v-if="publicShow" v-model="menuData" size="mini" label-width="100px">
            <el-form-item label="角色名：">
              <el-input v-model.trim="menuData.roleName" placeholder="请输入角色名" />
            </el-form-item>
            <el-form-item label="角色菜单：">
              <el-card style="height: 200px; overflow: auto">
                <el-tree ref="tree" :data="menuselectData" show-checkbox node-key="id" check-strictly accordion :props="defaultProps" :render-after-expand="false" @check-change="handleCheckChange"
                  @check="handleCheck" />
                <!-- @check="handlecheck" -->
              </el-card>
            </el-form-item>
            <el-form-item label="备注：">
              <el-input v-model.trim="menuData.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>

            <el-form-item>
              <el-button v-if="editMenuShow" type="primary" @click="editMenuClick">修改</el-button>
              <el-button v-if="addMenuShow" type="primary" @click="addMenuClick">新增</el-button>
              <!-- <el-button @click="cancelShow">取消</el-button> -->
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  queryRoleApi,
  addRoleApi,
  editRoleApi,
  delectRoleApi,
  queryMenu,
} from "@/api/manage";
import permission from "@/permission/index.js"; // 权限判断指令
import { Message } from "element-ui";
export default {
  name: "RoleManage",
  directives: { permission },
  data() {
    return {
      // 传输数据的 重置名字
      defaultProps: {
        children: "child",
        label: "menuName",
      },
      // 查询数据
      queryObj: {
        roleName: "",
        remark: "",
      },
      // 提交或者修改的数据
      menuData: {
        roleName: "", // 角色名称
        menus: [],
        remark: "",
      },
      listLoading: false,
      tableData: [],
      // 下拉框menu数据
      menuselectData: [],
      // 新增角色显示
      addMenuShow: true,
      // 编辑角色显示
      editMenuShow: false,
      // 公用角色显示
      publicShow: true,
      // 右侧编辑菜单名
      MenuName: "新增角色",
      // 判断右侧菜单是否显示
      demoData: 1,
    };
  },
  mounted() {
    this.queryData();
    this.getMenuData();
    // console.log(document.getElementById('rightcol'))
    if (document.getElementById("rightcol") === null) {
      this.demoData = 2;
    }
  },
  methods: {
    demo() {
      this.demoData = "llasdl";
    },
    /** 获取页面数据*/
    async queryData() {
      this.listLoading = true;
      const res = await queryRoleApi(this.queryObj);
      // console.log(res.data.data)
      this.tableData = res.data.data;
      this.listLoading = false;
    },
    // 获取menu下拉框数据
    async getMenuData() {
      const res = await queryMenu(this.queryObj);
      this.menuselectData = JSON.parse(JSON.stringify(res.data.data));
    },
    // 角色菜单数据点击的回调
    handleCheckChange(data, ischecked, ischild) {
      // console.log(data, '被点击的角色对应的数据')
      // console.log(ischecked, '本身是否被选中', ischild, '子数据是否被选中')
      // console.log(this.menuData.menus, 'this.menuData.menus')
      let parentData = []; // 父节点的数据
      if (data.parentId === 0) {
        parentData = data;
      }
      if (ischecked) {
        // console.log(data, '213')
        if (data.parentId !== 0) {
          if (!this.menuData.menus.includes(data.parentId)) {
            this.menuData.menus.push(data.parentId);
          }
        }
        // if(data.child.length)
        if (this.menuData.menus.includes(data.id)) {
          return;
        } else {
          this.menuData.menus.push(data.id);
        }
        // console.log(this.menuData.menus)
      } else {
        // console.log(this.menuData.menus.indexOf(data.id))
        const num = this.menuData.menus.indexOf(data.id);
        if (!ischild) {
          if (this.menuData.menus.indexOf(data.id) > -1) {
            this.menuData.menus.splice(num, 1);
          }
        }
        if (data.parentId !== 0) {
          // console.log(this.menuselectData, '所有菜单数据', data, '当前点击菜单数据')
          const filtermenus = this.menuselectData.filter(
            (item) => item.id === data.parentId
          );
          // console.log(filtermenus, '过滤出来的当前菜单的父级数据')
          const filtermenuschild = filtermenus.map((item) => item.child);
          console.log(
            filtermenuschild,
            "过滤出来的当前菜单的父级数据的子级数据"
          );
          var filtermenuschild2 = [];
          filtermenuschild2 = [].concat(...filtermenuschild);
          // console.log(filtermenuschild2, '过滤出来的当前菜单的父级数据的子级数据2')
          const childid = filtermenuschild2.map((item) => item.id);
          // console.log(...childid, '过滤出来的当前菜单的父级数据的子级数据的id')
          // console.log(this.menuData.menus, '当前菜单勾选的id')
          // console.log(this.menuData.menus.indexOf(...childid))
          // console.log(childid.map(item => this.menuData.menus.indexOf(item)))
          const ischildid = childid.map((item) =>
            this.menuData.menus.indexOf(item)
          );
          // console.log(ischildid.some(item => item !== -1))
          if (!ischildid.some((item) => item !== -1)) {
            // this.menuData.menus.splice(filtermenus[0].id, 1)
            // console.log(filtermenus, '过滤出来的当前菜单的父级数据')
            // console.log(filtermenus[0].id, '过滤出来的当前菜单的父级数据的id')
            this.menuData.menus = this.menuData.menus.filter(
              (item) => item !== filtermenus[0].id
            );
          }
        }
      }
      if (ischecked) {
        console.log(`选中了${data.menuName}-${data.id}`, data);
      } else {
        console.log(`选中了${data.menuName}-${data.id}`, data);
        const id = data.id;
      }
      console.log(this.menuData.menus, "当前菜单勾选的id");
      console.log(parentData, "父节点的数据");
    },
    handleCheck(data, status) {
      const menus = status.halfCheckedKeys;
      status.checkedKeys.forEach((d) => menus.push(d));
      this.menuData.menus = menus;
    },
    /* handleMenusCancle(data) {
      let id = data.id;
      if (id === 0) {
        this.menuData.menus.push(id);
      } else {

      }
      this.menuselectData;
    },
    handlecheck(data, node) {
      console.log(data, 'data')
      console.log(node, '树选中状态')
    }, */

    // 新增角色
    addMenu() {
      this.menuData = {
        roleName: "", // 角色名称
        menus: [],
        remark: "",
      };
      this.MenuName = "新增角色";
      this.editMenuShow = false;
      this.addMenuShow = true;
      this.publicShow = true;
      this.$refs.tree.setCheckedKeys([]);
    },
    // 新增角色确认按钮
    async addMenuClick() {
      if (this.menuData.remark.trim() === "" && this.menuData.roleName === "") {
        return Message.error("角色名等数据不能为空");
      }
      await addRoleApi(this.menuData);
      Message.success("新增成功");
      this.queryData();
      this.menuData = {
        roleName: "", // 角色名称
        menus: [],
        remark: "",
      };
      // console.log(this.menuData, 123)
    },
    // 编辑角色
    editRole(data) {
      this.MenuName = "编辑角色";
      this.addMenuShow = false;
      this.editMenuShow = true;
      this.publicShow = true;
      console.log(data, "点击角色的数据");
      this.menuData = {
        id: "",
        roleName: "", // 角色名称
        menus: [],
        remark: "",
      };
      this.menuData.id = data.id;
      this.menuData.roleName = data.roleName;
      this.menuData.remark = data.remark;
      this.menuData.menus = data.menus;
      // console.log(this.menuselectData, "所有权限页面的数据");
      // const allparentId = this.menuselectData.map((item) => item.id);
      // const allparentId = [];
      // this.menuselectData.forEach((d) => this.getParentId(d, allparentId));
      // console.log(allparentId, "所有父级的id", data.menus);
      // data.menus = data.menus.filter((id) => !allparentId.includes(id));
      this.$refs.tree.setCheckedKeys(data.menus, true);
      // console.log(data.menus, "将父级id过滤掉后的");
      // console.log(this.menuData, 222222222);
    },
    // 获取父节点的Id
    getParentId(data, arr) {
      if (data.child.length > 0) {
        // 有child添加id到数组
        arr.push(data.id);
        // 递归获取父节点Id
        data.child.forEach((d) => this.getParentId(d, arr));
      }
    },
    // 编辑角色的修改按钮功能
    async editMenuClick() {
      // console.log(this.menuData, '修改前数据显示', this.menuData)
      if (this.menuData.remark.trim() === "" && this.menuData.roleName === "") {
        return Message.error("角色名等数据不能为空");
      }

      await editRoleApi(this.menuData);
      Message.success("编辑成功");
      this.queryData();
      // this.menuData = {
      //   roleName: '', // 角色名称
      //   menus: [],
      //   remark: ''
      // }
    },
    // 编辑角色取消功能
    // cancelShow() {
    //   this.MenuName = '编辑角色'
    //   this.addMenuShow = false
    //   this.editMenuShow = false
    //   this.publicShow = false
    //   this.menuData = {
    //     roleName: '', // 角色名称
    //     menus: [],
    //     remark: ''
    //   }
    // },
    // 删除角色
    deleteRole(data) {
      if (data.roleName === "超级管理员") {
        return Message.error("无法删除此角色");
      }
      this.$confirm("确认删除该角色吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await delectRoleApi([data.id]);
          this.queryData();
        })
        .catch(() => {});
    },
    // 刷新按钮
    refreshClick() {
      this.listLoading = true;
      this.queryData();
      this.listLoading = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
<style lang="scss">
.ivu-tree-title {
  span {
    color: #000;
  }
}
</style>
<style scoped lang="scss">
.content-main {
  min-height: 88vh;
}
.left-content {
  padding: 5px;
}
.btn-group {
  display: flex;
  margin-bottom: 15px;
  margin-top: -7px;
}
.tree-group {
  // overflow-y: auto;
  height: inherit;
  max-height: 72vh;
  margin-top: 10px;
}
.title {
  min-height: 33px;
}
.form-title {
  display: flex;
  align-items: center;
}
</style>
